<template>
  <div id="signal-chart" style="width: 400px; height: 100px;"></div>
</template>

<script>
import * as echarts from "echarts";

export default {
  name: "SignalStrength",
  data() {
    return {
      chart: null,
      signalStrength: 30, // 代表信号强度，值为0-100
    };
  },
  mounted() {
    this.chart = echarts.init(document.getElementById("signal-chart"));
    this.updateChart();
  },
  methods: {
    getColorForStrength(strength) {
      const startColor = "#0299fb";
      const endColor = "#19e1c1";
      const percentage = strength / 100;

      // 计算颜色过渡
      const startRGB = [
        parseInt(startColor.slice(1, 3), 16),
        parseInt(startColor.slice(3, 5), 16),
        parseInt(startColor.slice(5, 7), 16),
      ];
      const endRGB = [
        parseInt(endColor.slice(1, 3), 16),
        parseInt(endColor.slice(3, 5), 16),
        parseInt(endColor.slice(5, 7), 16),
      ];

      const resultRGB = startRGB.map((start, index) =>
          Math.round(start + (endRGB[index] - start) * percentage)
      );

      return `rgb(${resultRGB[0]}, ${resultRGB[1]}, ${resultRGB[2]})`;
    },
    updateChart() {
      const option = {
        grid: {
          left: 0,
          right: 0,
          top: 0,
          bottom: 0,
        },
        xAxis: {
          show: false,
        },
        yAxis: {
          show: false,
        },
        series: [
          {
            type: "bar",
            data: [1, 1, 1, 1, 1], // 五个方块
            barWidth: "20%",
            itemStyle: {
              normal: {
                color: (params) => {
                  const idx = params.dataIndex;
                  const strengthPerBlock = this.signalStrength / 20;
                  const highlightedBlocks = Math.floor(strengthPerBlock); // 高亮的完整方块数
                  const partialBlock = strengthPerBlock - highlightedBlocks; // 部分高亮的方块

                  if (idx < highlightedBlocks) {
                    return this.getColorForStrength(this.signalStrength);
                  } else if (idx === highlightedBlocks && partialBlock > 0) {
                    return this.getColorForStrength(this.signalStrength * partialBlock);
                  }
                  return "#cccccc"; // 未高亮的方块颜色
                },
              },
            },
          },
        ],
      };

      this.chart.setOption(option);
    },
  },
  watch: {
    signalStrength() {
      this.updateChart();
    },
  },
};
</script>
